<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import TodoItem from '../components/TodoItem.vue';
import { useUserStore } from '../stores/user';
import type { TabsPaneContext } from 'element-plus'
import { update} from '../utils/request'
const activeName = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
const userStore = useUserStore();
//const todos = ref<string[]>(['Learn Vue', 'Build a project', 'Deploy the app']);

// 定义待办事项数组
const todos = ref<Object[]>([]);

// 定义新的待办事项输入
const newTodo = ref<string>('');
// 读取用户信息

// 设置用户信息
const setUser = () => {
  // 从 API 或其他地方获取用户信息
  const newUser = { name: 'John Doe', email: 'john@example.com' };
  userStore.setUser(newUser);
};

// 注销用户
const logout = () => {
  userStore.logout();
};

onMounted(async () => {
  try {
    const result = await fetch('/api/demo/getallitems');
    const data = await result.json();
    todos.value = data;
  } catch (error) {
    console.error('Error fetching todos:', error);
  }



  //  debugger
  // fetch('/api/demo/getallitems')
  // .then(response => response.json())
  // .then(data => {

  //   todos.value = data;
  // })
  // .catch(error => {
  //   console.error('Error fetching todos:', error);
  // });
})
// 添加待办事项
const addTodo = async () => {
  if (newTodo.value.trim()) {

    try {
      const newTodoItem = {
        title: newTodo.value,
        completed: false,
      };
      const result = await fetch('/api/demo/additem', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(newTodoItem)
      })

      const data=await result.json();
      if(data.id){
        newTodoItem.id=data.id;
      }
      todos.value.push(newTodoItem);

      //console.log('Todo added:', data);
    } catch (error) {
      newTodo.value = '';
      console.error('Error adding todo:', error);
    }

    //用async await方式发送添加数据的post请求


    //   fetch('/api/demo/additem', {
    //     method: 'POST',
    //     headers: {
    //       'Content-Type': 'application/json',
    //     },
    //     body: JSON.stringify({ title: newTodo.value,isComplete:false }),
    //   })
    //   .then(response => response.json())
    //   .then(data => {
    //     console.log('Todo added:', data);
    //   })
    //   .catch(error => {})
    //   newTodo.value = ''; // 清空输入框
    // 
  }
};

// 删除待办事项
const removeTodo = (id: number) => {

  const delIndex = todos.value.findIndex(item=>item.id==id);
  
  const delid = id;
 

  fetch('/api/demo/deleteitem', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ delid }),
  })
    //.then(response => response.json())
    .then(data => {
       todos.value.splice(delIndex, 1); // 根据索引删除待办事项
     // console.log('Todo deleted:', data);
    })
    .catch(error => {

      alert('del fail')

     })
};

// 计算剩余待办事项数量
const remainingTodos = computed(() => todos.value.length);



//const completed = ref<boolean[]>(todos.value.map(() => false));

const toggleComplete =async (id: number) => {
 // completed.value[index] = !completed.value[index];

  const index = todos.value.findIndex(todo => todo.id === id);
  todos.value[index].completed = !todos.value[index].completed

  await update(todos.value[index])
};


const notCompletedTodos = computed(() => todos.value.filter(todo => !todo.completed));


const completedTodos = computed(() => todos.value.filter(todo => todo.completed));
</script>

<template>
  <!-- {{ userStore.getUser }}
      <button @click="setUser">模拟登录</button> -->
  <div class="input-container">
    <input v-model="newTodo" @keyup.enter="addTodo" placeholder="Add a new todo" />
    <button @click="addTodo">Add</button>

    <p class="todo-count">Remaining Todos: {{ remainingTodos }}</p>

  </div>
  <!-- <div class="todo-list-container">
        <TodoList :todoArray="todos" @remove="removeTodo" />
      </div> -->
  <!-- Unordered list to display todo items -->


  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="未完成" name="first">

      <ul>
        <!-- TodoItem component for each todo item -->
        <TodoItem v-for="(todo, index) in notCompletedTodos" :key="index" :todo="todo" :id="todo.id"
          :completed="todo.completed" @remove="removeTodo(todo.id)" @toggleComplete="toggleComplete">

        </TodoItem>
      </ul>

    </el-tab-pane>



    <el-tab-pane label="已完成" name="second">
      <ul>
        <!-- TodoItem component for each todo item -->

        <TodoItem v-for="(todo, index) in completedTodos" :key="index" :todo="todo" :id="todo.id"
          :completed="todo.completed" @remove="removeTodo(todo.id)" @toggleComplete="toggleComplete">

        </TodoItem>

      </ul>



    </el-tab-pane>

  </el-tabs>



</template>

<style scoped>
/* Delete: 原有的样式保持不变 */
/* ... existing code ... */
</style>
